package com.motionlog.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.motionlog.R;
import com.motionlog.model.Base;
import com.motionlog.model.Database;

public class CognitiveTherapy extends Activity implements OnClickListener {

	private static final String TAG = null;
	private static final String LOG_TAG = null;
	Button method;
	ArrayList<Base> categories = new ArrayList<Base>();
	EditText description;
	TextView selectedCategories;

	private Button mRecord;

	Intent preIntent;

	Database mDb;

	long logId;
	private String summary = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cognitive_therapy);

		mDb = Database.getInstance(this);

		Button controll = (Button) findViewById(R.id.controll);
		controll.setOnClickListener(this);
		Button uncontroll = (Button) findViewById(R.id.uncontroll);
		uncontroll.setOnClickListener(this);

		mRecord = (Button) findViewById(R.id.record);
		mRecord.setOnClickListener(this);

		description = (EditText) findViewById(R.id.description);

		selectedCategories = (TextView) findViewById(R.id.selected_categories);

		Button back = (Button) findViewById(R.id.back);
		back.setOnClickListener(this);

		method = (Button) findViewById(R.id.method);
		method.setOnClickListener(this);

		// i.putExtra("motion", curentMotion);
		// i.putExtra("reason-ids", reasonIds);
		// i.putExtra("level", level.getProgress());
		preIntent = getIntent();
	}

	private void updateDbLog(int step) {
		int motionId = preIntent.getIntExtra("motion_id", -1);
		int level = preIntent.getIntExtra("level", -1);
		String summary = preIntent.getStringExtra("summary");
		android.util.Log.d(TAG, "motionId: " + motionId + ", summary: "
				+ summary);
		ArrayList<Base> reasons = preIntent
				.getParcelableArrayListExtra("reasons");
		ArrayList<Base> methods = preIntent
				.getParcelableArrayListExtra("methods");
		String desc = preIntent.getStringExtra("description");
		String remark = preIntent.getStringExtra("remark");

		// log and reasons
		final long logId = mDb.insertLog(motionId, level, summary);
		for (Base reason : reasons) {
			mDb.insertReasonLog(logId, reason.id);
		}

		// methods
		for (Base method : methods) {
			mDb.insertMethodLog(logId, method.id);
		}
		mDb.updateLog(logId, desc, remark, summary);

		// categories
		for (Base category : categories) {
			mDb.insertCategoryLog(logId, category.id);
		}
		mDb.updateLog(logId, description.getText().toString(), summary);

		// step
		mDb.updateLogFinishStep(logId, step);

		String descRecord = getIntent().getStringExtra("record-desc");
		if (TextUtils.isEmpty(descRecord)) {
			File recordFile = new File(descRecord);
			recordFile.renameTo(new File(recordFile.getAbsolutePath()
					+ "/log.method.desc." + logId + ".3gp"));
		}

		if (TextUtils.isEmpty(mFileName)) {
			File recordFile = new File(descRecord);
			recordFile.renameTo(new File(recordFile.getAbsolutePath()
					+ "/log.category.nowthink." + logId + ".3gp"));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.controll: {
			if (TextUtils.isEmpty(description.getText().toString())
					|| categories.size() == 0) {
				Toast.makeText(CognitiveTherapy.this, "请填写相应字段",
						Toast.LENGTH_LONG).show();
				return;
			}
			updateDbLog(2);

			Intent i = new Intent(this, ThrowEnvl.class);
			i.putExtras(preIntent);
			startActivity(i);
		}
			break;
		case R.id.uncontroll: {
			if (TextUtils.isEmpty(description.getText().toString())
					|| categories.size() == 0) {
				Toast.makeText(CognitiveTherapy.this, "请填写相应字段",
						Toast.LENGTH_LONG).show();
				return;
			}
			updateDbLog(3);
			Intent i = new Intent(this, Home.class);
			i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			i.putExtra("tab-index", 3);
			startActivity(i);
			finish();
		}
			break;
		case R.id.method: {
			startActivityForResult(new Intent(CognitiveTherapy.this,
					SelectCognitiveCategory.class), 0);
		}
			break;
		case R.id.back:
			finish();
			break;
		case R.id.help:
			//
			break;
		case R.id.record:
			if (mIsRecord) {
				stopRecording();
				mRecord.setBackgroundResource(R.drawable.record);
			} else {
				startRecording("nowthink");
				mRecord.setBackgroundResource(R.drawable.stop);
			}
			mIsRecord = !mIsRecord;
			break;
		default:
			break;
		}
	}

	MediaRecorder mRecorder;
	String mFileName = null;
	boolean mIsRecord = false;

	private void startRecording(String name) {
		mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
		mFileName += "/Android/data/com.motionlog/record";
		mFileName += "/temp." + name + ".3gp";

		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setOutputFile(mFileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		try {
			mRecorder.prepare();
		} catch (IOException e) {
			android.util.Log.e(LOG_TAG, "prepare() failed");
		}

		mRecorder.start();
	}

	private void stopRecording() {
		mRecorder.stop();
		mRecorder.release();
		mRecorder = null;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0:
			if (resultCode == RESULT_OK) {
				summary = data.getStringExtra("summary");
				categories = data.getParcelableArrayListExtra("categories");
				selectedCategories.setText(summary);
			}
			break;
		default:
			break;
		}
	}
}
